package com.course.android.activity.ac;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.bluetooth.BluetoothAdapter;
import android.widget.Toast;
import android.util.Log;
import android.Manifest;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.course.android.R;
import com.course.android.activity.base.BaseActivity;
import com.course.controller.BluetoothController;
import com.course.controller.TestController;


import java.util.Set;

public class BluetoothActivity extends BaseActivity {


    private BluetoothAdapter mBluetoothAdapter;
    @Override
    protected void initView() {
        //判断是否有访问位置的权限，没有权限，直接申请位置权限
        isPermission();

        //判断是否有蓝牙的权限，蓝牙动态申请权限
//        initPermission();
        //初始化蓝牙适配器
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();


        if (isBluetoothSupport()){
            Toast.makeText(BluetoothActivity.this, "该设备支持蓝牙功能", Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(BluetoothActivity.this, "该设备不支持蓝牙功能", Toast.LENGTH_SHORT).show();
        }

        //判断蓝牙是否打开
        if(!isBluetoothEnabled()){
            //如果蓝牙未开启，则申请打开蓝牙
            Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBluetoothIntent, RESULT_CANCELED);
        }else {

        }



    }
    //动态获取位置权限
    @SuppressLint("NewApi")
    private void isPermission() {
        if ((checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
                || (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
                || (checkSelfPermission(Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED)
                || (checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED)
                || (checkSelfPermission(Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED)
                || (checkSelfPermission(Manifest.permission.BLUETOOTH_ADVERTISE) != PackageManager.PERMISSION_GRANTED)) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_ADVERTISE}, 200);
        }
        //请求蓝牙权限
//        if ((checkSelfPermission(Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED)
//                || (checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED)
//                || (checkSelfPermission(Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED)
//                || (checkSelfPermission(Manifest.permission.BLUETOOTH_ADVERTISE) != PackageManager.PERMISSION_GRANTED)) {
//            requestPermissions(new String[]{Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_ADVERTISE}, 200);
//        }
    }


    //判断该设备是否支持蓝牙功能
    private Boolean isBluetoothSupport(){
        if(mBluetoothAdapter == null){
            return false;
        }else {
            return true;
        }
    }

    /**
     * 检查该设备蓝牙是否开启
     */
    private boolean isBluetoothEnabled() {
        if (mBluetoothAdapter.isEnabled()) {
            return true;
        } else {
            return false;
        }
    }

        @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_CANCELED) {
            if (resultCode == RESULT_OK) {
                // 蓝牙已成功开启
                Toast.makeText(BluetoothActivity.this, "用户已开启蓝牙", Toast.LENGTH_SHORT).show();
            } else {
                // 用户取消了蓝牙开启请求
                Toast.makeText(BluetoothActivity.this, "用户已拒绝开启蓝牙", Toast.LENGTH_SHORT).show();
            }
        }
    }

        @Override
    protected void initData() {

    }

    @Override
    protected int bindLayout() {
        return R.layout.activity_bluetooth;
    }

    @Override
    protected void onActivityResultCallBack(Integer reqCode, Intent data) {

    }

    public void onClick(View view) {
        if (view.getId() == R.id.btlistbtn) {
            //普通请求
//            TestController.getInstance().test("HttpActivity", this);
            BluetoothController.getInstance().btDeviceListGet();
            getPairedDevices();
        }
        if (view.getId() == R.id.btpairbtn) {
            //页面请求
//            TestController.getInstance().testPage(this);
            BluetoothController.getInstance().btDevicePair();
            mBluetoothAdapter.startDiscovery();
            registerBluetoothReceiver();
        }
    }

    @SuppressLint("MissingPermission")
    private void getPairedDevices() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            int i = 0;
            for (BluetoothDevice device : pairedDevices) {
                i++;
                if(i == pairedDevices.size()){
                    device.createBond();
                    Log.d("","本机与另一个蓝牙设备"+device.getName()+"配对成功");
                }
                String deviceName = device.getName();
                String deviceHardwareAddress = device.getAddress();
                Log.d("BluetoothActivity","设备名："+deviceName+'\n'+"地址："+deviceHardwareAddress);
            }
        }
    }

    private void registerBluetoothReceiver(){
        //filter注册广播接收器
        IntentFilter filter = new IntentFilter();


        //蓝牙当前状态
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);


        //开始扫描蓝牙设备广播
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);

        //找到蓝牙设备广播
        filter.addAction(BluetoothDevice.ACTION_FOUND);

        //扫描蓝牙设备结束广播
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

        //蓝牙设备配对状态改变广播
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);

        //设备扫描模式改变广播
        filter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);

        registerReceiver(receiver, filter);
    }


    //处理找到蓝牙设备和搜索完成的广播消息
    BroadcastReceiver receiver = new BroadcastReceiver() {

        @SuppressLint("MissingPermission")
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            //开始查找设备
            if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
                Log.d("","开始查找");
            }
            //找到蓝牙设备
            else if(BluetoothDevice.ACTION_FOUND.equals(action)){
                //搜到蓝牙设备
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                //把搜索到的设备添加到已找到列表中，显示它的信息
                Log.d("","设备名："+device.getName()+'\n'+"地址："+device.getAddress());

            }
            //查找设备结束
            else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
                //搜索完毕
                Toast.makeText(BluetoothActivity.this, "选择要配对的蓝牙设备", Toast.LENGTH_SHORT).show();
                Log.d("","查找结束");
            }

        }
    };




}